/*
 * DistributeTest.java
 *
 * Created on March 11, 2007, 2:42 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor. */

package ca.uvic.group2.testHarness;
import java.util.*;
import java.io.*;
/**
 *
 * @author pat
 */
public class DistributeTest {

    private DistributeTest() {
    }


    public static String[] userPerFile(String filename, HashMap outFiles, boolean isRemote) {
       String nextLine, uname;
       StringTokenizer sToken;
       BufferedWriter out;
       int fileCount = 0;
       ArrayList<String> filenames = new ArrayList<String>();
       String username = System.getenv("USER");

       try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            nextLine = in.readLine();
            while(nextLine != null) {
                sToken = new StringTokenizer(nextLine, ",");
                uname = sToken.nextToken();
                uname = (sToken.nextToken()).trim();
                if(uname.equals("./testLOG"))
                    break;
                if(!outFiles.containsKey(uname)) {
                    String outFileName = username + "-user" + ++fileCount + ".txt";
                    if (isRemote) {
                        outFileName = "/tmp/" + outFileName;
                    }
                    out = new BufferedWriter(new FileWriter(outFileName));
                    filenames.add(outFileName);
                    out.write("[0] LOGIN, " + uname + ", pass");
                    out.newLine();
                    outFiles.put(uname, out);

                    //Init User in DB
                    //WSConnectionManager init = new WSConnectionManager();
                    //init.commandUserInit(uname);
                }//endIf
                out = (BufferedWriter) outFiles.get(uname);
                out.write(nextLine);
                out.newLine();
                nextLine = in.readLine();
            } //endWhile

            Set s = outFiles.keySet();
            Iterator i = s.iterator();
            while(i.hasNext()) {
                uname = (String) i.next();
                out = (BufferedWriter) outFiles.get(uname);
                out.write("[0] LOGOUT, " + uname);
                out.newLine();
                ((BufferedWriter) outFiles.get(uname)).close();
            }//endWhile
            in.close();

        } catch (IOException e) {
            //debugLog.debug("File Not Found!/Could not create file!");
            e.printStackTrace();
            System.exit(0);
        }//endTryCatch

       String[] returnFilenames = new String[filenames.size()];
       filenames.toArray(returnFilenames);
       return returnFilenames;
    }//endMethod

    private static class UserFile {
        public BufferedWriter out;
        public String filename;
        public int numCommands = 0;

        public UserFile(BufferedWriter out, String filename) {
            this.out = out;
            this.filename = filename;
        }
    }


    /**
     * @param args the command line arguments
     */
    public static String[] initBreakUp(String filename, HashMap unameMap, int usersPerFile) {
        return initBreakUp(filename, unameMap, usersPerFile, 0, 0);
    }

    public static String[] initBreakUp(String filename, HashMap unameMap, int usersPerFile, int maxUsers, int maxCommands) {
        return initBreakUp(filename, unameMap, usersPerFile, maxUsers, maxCommands, true);
    }

    public static String[] initBreakUp(String filename, HashMap unameMap, int usersPerFile, int maxUsers, int maxCommands,
                                       boolean doLogin) {
        // TODO code application logic here
        String nextLine, uname;
        StringTokenizer sToken;
        int userCount = 0;
        UserFile out, current = null;
        LinkedList outfiles = new LinkedList();
        int numFiles = 0;
        ArrayList<String> filenames = new ArrayList<String>();
        //divide big file into 20
        try {
            // First Pass  - Find users, create files, add LOGIN commands
            BufferedReader in = new BufferedReader(new FileReader(filename));
            userCount = 0;

            for (nextLine = in.readLine(); nextLine != null; nextLine = in.readLine()) {
                if (nextLine.contains("DUMPLOG")) {
                    break;
                }

                sToken = new StringTokenizer(nextLine, ",");
                uname = sToken.nextToken();
                uname = (sToken.nextToken()).trim();

                //File that this line need to be put in is userCount/Maxuser
                if(!unameMap.containsKey(uname)) {

                    // Limit the number of users, if maxUsers specified
                    if (maxUsers > 0 && userCount >= maxUsers) {
                        continue;
                    }

                    if(userCount % usersPerFile == 0) {
                        String outFilename = "user" + (++numFiles) + ".txt";
                        filenames.add(outFilename);
                        out = new UserFile(new BufferedWriter(new FileWriter(outFilename)), filename);
                        unameMap.put(uname, out);
                        current = out;
                    } else {
                        unameMap.put(uname, current);
                    }
                    if (doLogin) {
                        out = (UserFile)unameMap.get(uname);
                        out.out.write("[0] LOGIN, " + uname + ", pass");
                        out.out.newLine();
                    }
                    userCount++;
                    //Init User in DB
                    //WSConnectionManager init = new WSConnectionManager();
                    //init.commandUserInit(uname);
                }
            }//endWhile
            in.close();

            // Second Pass - Add workload commands to user files.
            in = new BufferedReader(new FileReader(filename));

            for (nextLine = in.readLine(); nextLine != null; nextLine = in.readLine()) {
                if (nextLine.contains("DUMPLOG")) {
                    break;
                }

                sToken = new StringTokenizer(nextLine, ",");
                uname = sToken.nextToken();
                uname = (sToken.nextToken()).trim();

                //File that this line need to be put in is userCount/Maxuser
                if(!unameMap.containsKey(uname)) {
                    continue;
                }

                out = (UserFile)unameMap.get(uname);

                // Limit number of transactions, if maxCommands is greater than 0
                if (maxCommands <= 0 || out.numCommands < maxCommands) {
                    out.out.write(nextLine);
                    out.out.newLine();
                    ++out.numCommands;
                }
            }//endWhile

            Set s = unameMap.keySet();
            Iterator i = s.iterator();
            while(i.hasNext()) {
                uname = (String) i.next();
                out = (UserFile) unameMap.get(uname);
                if (doLogin) {
                    out.out.write("[0] LOGOUT, " + uname);
                    out.out.newLine();
                }
                outfiles.add(out);
            }//endWhile
            in.close();

            i = outfiles.iterator();
            while(i.hasNext()) {
                out = (UserFile) i.next();
                out.out.close();
            }//endWhile

        } catch (IOException e) {
            System.out.println("Failed to Open file for Reading");
            e.printStackTrace();
            System.exit(1);
        }//endTryCatch

        String[] returnFilenames = new String[filenames.size()];
        return filenames.toArray(returnFilenames);

        //separate out directories
        //run testharness on those peers
        //wait until completeion of all tests
        //call it a day
    }//endMethod

}//endClass
